;
(function () {
  'use strict';
  angular.module('services.userBehaviorAnalysis.userChurnAnalysis')
    .service('userChurnRateAnalysisService', userChurnRateAnalysisService);
  function userChurnRateAnalysisService($http, $filter, CoreService, $timeout,CoreLoading) {
    var time = new Date();
    var startDate = new Date(time.getFullYear(), time.getMonth() - 6);
    var endDate = new Date(time.getFullYear(), time.getMonth() - 3);
    //页面参数
    this.params = {
      startTime: startDate,
      endTime: endDate
    };

    this.arrow = false;
    this.churnRateDataList = [];  //告警数据集合
    this.showSearchPanel = true;//显示查询面板
    this.re = 'false';
    this.showIcon = true;   //控制显示折线和表格的图标
    this.viewType = 'chart';//默认折线视图类型
    this.title = null;  //图表和表格显示的标题
    var chart = null;   //折线图

    var dayCount = 0; //保存查询数据的总天数
    var dataList = [];   //临时数据集合
    var that = this;
    var param = {}; //临时参数对象
    /**
     * 隐藏查询面板
     */
    this.hideSearchPanel = function () {
      this.showSearchPanel = false;
    };
    /**
     * 清空页面旧值
     */
    this.reset = function () {
      that.arrow = false;
      that.showSearchPanel = true;
      that.viewType = 'chart';
      that.params.startTime = startDate;
      that.params.endTime = endDate;
      that.churnRateDataList = [];
      that.dataList = [];
      chart && chart.clear();  //折线图表数据清空
      that.showIcon = false;
    };
    /**
     * 查询 告警数据分业务进行分析对比
     */
    this.initfn=function(){
      that.reset();
      that.showSearchPanel=true;
      that.search();
    };

    this.sendData = null;
    this.search = function () {
      //收起查询面板
      if (!that.showSearchPanel) {
        that.showSearchPanel = true;
        return;
      }

      //copy页面参数 格式化参数
      param = angular.copy(that.params);
      param.startTime = $filter('date')(param.startTime, 'yyyy-MM');
      param.endTime = $filter('date')(param.endTime, 'yyyy-MM');
      //页面标题显示方式
      if(param.startTime===param.endTime){
        that.title = $filter('date')(that.params.startTime, 'yyyy年MM月') + ' 各业务线用户流失率趋势';
      }else{
        that.title = $filter('date')(that.params.startTime, 'yyyy年MM月') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月') + ' 各业务线用户流失率趋势';
      }
      CoreLoading.setState(true);
      $http.post('/sas/analysisUserBehavior/userChurnRate/queryChurnRate', param)
        .then(function (res) {
          that.showSearchPanel = false;   //收缩查询面板
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            dataList = res.data.data;
            that.changeViewType();  //默认显示折线图表
            that.showIcon = true; //显示表格和折线图标
            that.arrow = false;
          } else {
            that.PageDisplayStyle();
            CoreService.dialog('查询无数据');
            that.arrow = true;
          }
          CoreLoading.setState(false);
        });
    };

    //初始化折线图数据
    function initChart() {
      var busLineList = ['天猫旗舰店', '移动商城', '银行总对总'];

      chart = echarts.init(document.getElementById('userChurnRateAnalysisChart'));
      var option = {
        animation:false,
        title: {
          text: that.title,
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (param) {
            return param.name + '<br/>' + param.seriesName + ': ' + param.value + '%';
          }
        },
        legend: {data: busLineList, x: 'right', y: 'center', orient: 'vertical'},
        xAxis: [{type: 'category', data: [], splitLine: {show: false}}],
        yAxis: [
          {
            name: '用户流失率',
            type: 'value',
            axisLabel: {
              formatter: '{value}' + '%'
            }
          }
        ],
        series: [],
        grid: {x: '104', x2: '128'}
      };

      //横轴显示数据
      var x = [];
      angular.forEach(dataList, function (data) {
        x.push(data.time);
      });
      option.xAxis[0].data = x;

      //返回数据显示
      var obj = {};
      angular.forEach(busLineList, function (bl) {
        obj[bl] = [];
      });
      angular.forEach(dataList, function (dl) {
        obj['天猫旗舰店'].push(dl.tmallRate.substring(0, dl.tmallRate.length - 1));
        obj['移动商城'].push(dl.mallRate.substring(0, dl.mallRate.length - 1));
        obj['银行总对总'].push(dl.bankRate.substring(0, dl.bankRate.length - 1));
      });

      angular.forEach(busLineList, function (key, index) {
        option.series[index] = {
          name: key,
          type: 'line',
          data: obj[key]
        }
      });
      chart.setOption(option);
      //导出；
      $timeout(function(){
        that.sendData=onSubmit();
      },1000);
    };

    /**初始化表格*/
    function initTable() {
      var list = [];
      var x = [];
      angular.forEach(dataList, function (data) {
        x.push(data.time);
      });
      angular.forEach(x, function (datetime) {
        var row = [datetime];
        angular.forEach(dataList, function (data) {
          if (datetime === data.time) {
            row.push(data.tmallRate, data.mallRate, data.bankRate);
          }
        });
        list.push(row);
      });
      that.churnRateDataList = list;
    };

    //查询无数据时页面的样式
    this.PageDisplayStyle = function () {
      that.showSearchPanel = true;   //显示查询面板
      that.showIcon = false;  //隐藏表格和折线图标
      dataList = [];  //数据清空
      that.churnRateDataList = [];
      chart && chart.clear();  //折线图表数据清空
    }
    //控制显示折线或者表格
    this.changeViewType = function (type) {
      initChart();
      var ta=document.getElementById('ta');
      var cha=document.getElementById('cha');
      that.viewType = type || that.viewType;
      if (that.viewType === 'chart') {
        $timeout(initChart, 0);
        ta.style.backgroundColor = "";
        cha.style.backgroundColor = "#2196F3";
      } else if (that.viewType === 'table') {
        ta.style.backgroundColor = "#2196F3";
        cha.style.backgroundColor = "";
        initTable();
      }
    };
    /**导出excel*/
    function onSubmit() {
      var data = {
        startTime: $filter('date')(that.params.startTime, 'yyyy-MM'),
        endTime: $filter('date')(that.params.endTime, 'yyyy-MM'),
        title: that.title,
        base64s: [chart.getDataURL('png').split(',')[1]],
      };
      return JSON.stringify(data);
    };
  }

  userChurnRateAnalysisService.$inject = ['$http', '$filter', 'CoreService', '$timeout','CoreLoading'];
})
();